﻿var ImageObj=new Image();
var Lat={
    Data:{"0":null},
    Cache:{},
    _Data:null,
    DefaultDesk:0,
    State:0,
    DragState:0,
    User:{},
    PosData:{},
    ContainerPos:{},
    Draging:false,
    DragElement:0,
    TargetElement:null,
    TempElement:null,
    AddSiteId:null,
    SiteFormData:{},
    ShowAction:false,
    ActionName:null,
    init:function(data){
        jQuery.extend(this.Data,this._Data[this.DefaultDesk].data);
        this.ContainerPos=$('#site-container').position();
        $("#dropBox").easydrag(true);
        $("#dropBox").ondrop(function(e,element){
            if(Lat.ActionName){
                Lat.cmd(Lat.ActionName);
            }else{
                Lat._drag(element);
            }
            setTimeout(function(){$('#search-box').show();},300);
            return false;
        }).mouseover(function(e){
                if($.browser.msie)window.status=Lat.Data[Lat.DragElement][2];
                return false;
        }).mouseout(function(e){
                Lat.mouseOutBox();
                return false;
        }).ondrag(function(e){
                Lat.Draging=true;
                if(!Lat.ShowAction)Lat._dragShowAction();
                Lat._getTarget(e);
                return false;
        }).click(function(e){
                Lat.clickBox(Lat.DragElement);
                return false;
        });
        $('#site-container .site-box').mouseover(function(e){
            Lat.mouseOverBox(this);
            return false;
        });
        $('.dialogCancel').click(function(e){
            tb_remove();
            return false;
        });
        $("#addIcon").click(function(e){
            Lat.addSite();
        }).mouseout(function(e){
            $(this).css({left:-5000});
            return false;
        });
        this.initDesk();
        this.initDeskTab();
        if(this.State==2){
            this.initAddSite();
            this.initSetDeskBg();
        }
        if(this.State>0){
            this.initSetting();
            this.initCopySite();
            this.initAddDesk();
        }
        if(this.State==0){
            this.initLogin();
            this.initReg();
        }
        $(window).unbind('resize').resize(function(){
            Lat.resize();
        });
    },
    resize:function(){
        var temp=$H(Lat.ContainerPos);
        this.ContainerPos=$('#site-container').position();
        if(this.ContainerPos.left!=temp.left){
            $('#dropBox').hide();
            $H(this.PosData).each(function(p,index){
                Lat.PosData[index][0]=p.value[0]-(temp.left-Lat.ContainerPos.left);
                Lat.PosData[index][3]=p.value[3]-(temp.left-Lat.ContainerPos.left);
                });
        }
    },
    showMessage:function(msg,closeDialog,showTime){
        var m=$('#systemMessage');
        var w=$(window);
        var l=(w.width()-m.outerWidth(true))/2;
        var t=$(document).scrollTop()+(w.height()-m.outerHeight(true))/2;
        m.html(msg).css({left:l,top:t}).show().fadeOut(showTime||2000);
        if(closeDialog)tb_remove();
            return false;
    },
    initSetting:function(){
        $('#settingOk').click(function(e){
            var data=$('#settingForm').serialize();
            jQuery.post('?action=userSetting',data,function(result){
            if(result.err){
                $('#settingErr').html(result.err);
            }else{
                Lat.showMessage('设置成功',true);
                location.reload();
            }
        },'json');
        return false;
        });
    },
    initCopySite:function(){
        $('#copySiteOk').click(function(e){
            var dataStr=$('#copySiteForm').serialize();
            jQuery.post('?action=copySite',dataStr,function(result){
            if(result.err){
                Lat.showMessage(result.err);
            }else{
                var pram=dataStr.toQueryParams();
                for(var i=0;i<52;i++){
                    if(!Lat._Data[pram.targetDeskId].data[i]){
                        Lat._Data[pram.targetDeskId].data[i]=Lat.Data[pram.siteIndex];
                        break;
                    }
                }
                Lat.showMessage('成功复制到目标桌面',true);
            }},'json');
            return false;
        });
    },
    
    initDeskTab:function(){
        $('#desk-bar a').click(function(e){
            var id=$(this).blur().attr('rel');
            if(id!=Lat.DefaultDesk)Lat.initDesk(id);
            return false;
        }).mouseover(function(e){
            var element=$(this);
            var deskId=element.attr('rel');
            if(Lat.DefaultDesk==deskId){
                Lat.Cache.showDeskOpt=true;
                var pos=element.position();
                $('#deskOpt').css({left:pos.left+1,top:pos.top+element.outerHeight()}).show();
            }
            return false;
        }).mouseout(function(e){
            var element=$(this);
            var deskId=element.attr('rel');
            if(Lat.DefaultDesk==deskId){
                Lat.Cache.showDeskOpt=false;
                setTimeout(function(){
                if(!Lat.Cache.showDeskOpt)$('#deskOpt').hide();
                },100);
            }
            return false;
        });
        $('#deskOpt a').mouseover(function(e){
            Lat.Cache.showDeskOpt=true;
            return false;
        }).mouseout(function(){
            Lat.Cache.showDeskOpt=false;
            setTimeout(function(){
            if(!Lat.Cache.showDeskOpt)$('#deskOpt').hide();
            },100);
            return false;
        });
        $('#search-box img').click(function(e){
            $('#search-box img').show();
            var target=$(this).hide().attr('alt');
            $('#search-box').attr('class','search-box '+target);
            $('#search-iframe').attr('src',$('#search-iframe').attr('src').replace(/[^_]*\.html/,target+'.html'));
            return false;
        });
    },
    
    initDesk:function(id){
        id=id||this.DefaultDesk;
        if(id){
            this.DefaultDesk=id;
            this.Data=this._Data[id].data;
            $('#desk-bar a').each(function(){
                var e=$(this);
                if(e.attr('rel')==id){
                    e.parent().addClass('on');
                }else{
                    e.parent().removeClass('on');
                }
            });
            $("#dropBox").hide();
            $("#addIcon").hide();
        }else{
            id=this.DefaultDesk;
        }
        $('#site-container .site-box').each(function(index){
            Lat.initBox(index);
            if(Lat.PosData['51'])return;
            var pos=$(this).position();
            Lat.PosData[index]=[pos.left,pos.top+10,pos.left+80,pos.top+90];
        })
    },
    
    
    initBox:function(id){
        var data=this.Data[id];
        if(data){
            ImageObj.src=data[4];
            $('#'+id).html('<div class="icon '+data[3]+'"><div class="icon-content" style="background-image:url('+data[4]+');'+(data[5]?' color:'+data[5]:'')+'" rel="'+data[2]+'"><div class="icon-inner">'+data[1]+'</div></div></div>');
        }else{
            $('#'+id).empty();
        }
    },
    initAddDesk:function(){
        $('#addDeskOk').click(function(e){
            tb_remove();
            jQuery.post('?action=updateDesk',$('#addDeskForm').serialize(),function(id){location.href='?'+id;});
            return false;
        });
        $('#editDeskOk').click(function(e){
            tb_remove();
            var data=$('#editDeskForm').serialize().toQueryParams();
            data.defaultDesk=data.defaultDesk||0;
            data.noShare=data.noShare||0;
            $('#desk-bar .on a').html(data.title);
            Object.extend(Lat._Data[Lat.DefaultDesk],data);
            jQuery.post('?action=updateDesk',$H(data).toQueryString());
            return false;
         });
        $('#delDeskOk').click(function(e){
            if($H(Lat._Data).size()==1){
                Lat.showMessage('老兄，您已经只有一个桌面了，就放过它吧');
            }else{
                $('#desk-bar li.on').remove();
                var deskId=$C(Lat.DefaultDesk);
                Lat._Data=$H(Lat._Data).lost(deskId);
                Lat.initDesk(Lat._Data.keys()[0]);
                tb_remove();
                jQuery.post('?action=delDesk','id='+deskId);
            }
            return false;
        });
        $('#copyDeskOk').click(function(e){
             jQuery.post('?action=updateDesk','sourceId='+Lat.DefaultDesk+'&'+$('#copyDeskForm').serialize(),function(){
                if(Lat.State==2){
                    location.reload();
                }else{
                    Lat.showMessage('桌面复制成功',true);
                }
            });
            return false;
        });
        $('#deskOpt .edit').click(function(e){
            initForm(Lat._Data[Lat.DefaultDesk],'editDeskForm');
        });
    },
    initLogin:function(){
        $('#login .showRegDialog').click(function(e){
            tb_remove();
            setTimeout(function(){ $('#regDialog').click();},300);
            return false;
        });
        $('#loginOk').click(function(e){
            var data=$('#loginForm').serialize();
            jQuery.post('?action=userLogin',data,function(result){
                if(result.err){
                $('#loginErr').html(result.err);
                }else{
                location.reload();
                }
            },'json');
            return false;
        });
    },
    initReg:function(){
        $('#reg .showLoginDialog').click(function(e){
            tb_remove();
            setTimeout(function(){
            $('#loginDialog').click();
            },300);
            return false;
        });
        $('#regOk').click(function(e){
            jQuery.post('?action=userReg',$('#regForm').serialize(),function(result){
            if(result.err){
            $('#regErr').html(result.err);
            if(result.err=='验证码填写错误！')$('#validateCode').click();
            }else{
            Lat.showMessage(result.msg,true);
            setTimeout(function(){
            $('#loginDialog').click();
            },300);
            }
            },'json');
            return false;
        });
        $('#validateCode').click(function(e){
            var codeKey=new Date().getTime();
            $('#codeKey').val(codeKey);
            this.src=this.src.replace(/\d+$/,codeKey);
        });
    },
    initAddSite:function(){
        var demo=$('#site-icon-demo');
        $('#site-name').keyup(function(e){
            $('.icon-inner',demo).html($(this).val());
        });
        $('#icon-bg-selete a').click(function(e){
            var color=$(this).attr('color');
            Lat.SiteFormData.bgColor=color;
            demo.attr('class','icon '+color);
            return false;
        });
        $('#addSiteOk').click(function(e){
            Lat.SiteFormData.url=$('#site-url').val();
            Lat.SiteFormData.title=$('#site-name').val();
            Lat.updateSite(Lat.UpdateSiteId,Lat.SiteFormData);
            Lat.showMessage('添加成功',true);
            return false;
        });
        $("#icon-type-default, #icon-type-upload").click(function(e){
            $("#icon-upload, #icon-default").hide();
            $('#'+$(this).attr('id').replace('-type','')).show();
        });
        $('#uploadForm .submit').click(function(e){
            if($("#uploadForm input[name='file']").val()){
                $('#uploadForm').submit();
            }
            return false;
        });
        $('#showRecommendSiteDialog').click(function(e){
            Lat.Cache.DragElement=Lat.DragElement;
            tb_remove();
            setTimeout(function(){$('#recommendSiteDialog').click();},300);
            return false;
        });
        $('#showAddSiteDialog').click(function(e){
            tb_remove();
            setTimeout(function(){$('#addIconDialog').click();},300);
            return false;
        });
        $('#recommendSite .icon').click(function(e){
            var site=$(this);
            var data=site.attr('data').split('^');
            Lat.SiteFormData.title=data[0];
            Lat.SiteFormData.url=data[1];
            Lat.SiteFormData.bgColor=data[2];
            Lat.SiteFormData.icon=data[3];
            Lat.SiteFormData.titleUrl=data[4];
            Lat.updateSite(Lat.UpdateSiteId,Lat.SiteFormData);
            Lat.showMessage('添加成功',true);
            return false;
        });
    },
    initAddSiteData:function(o){
        var demo=$('#site-icon-demo');
        if(o){
            o={
                id:o[0],
            title:o[1],
            url:o[2],
            bgColor:o[3],
            icon:o[4],
            titleColor:o[5]
            };
        }
        var data={
            url:'http://',
            title:'',
            bgColor:'white',
            icon:'',
            titleColor:''
        }
        jQuery.extend(data,o);
            this.SiteFormData=data;
            $('#site-name').val(data.title);
            $('#site-url').val(data.url);
            demo.attr('class','icon '+data.bgColor);
            $('.icon-content',demo).css({
            'background-image':'url('+data.icon+')',
            'color':data.titleColor
        });
        $('.icon-inner',demo).html(data.title);
        if($('#default-icon-selete').html()==''){
            var str=$R(1,76).map(function(n){
                 ImageObj.src='/Public/Site/Icon/'+n+'.gif';
                    return'<a href="#" id="default-icon-'+n+'" style="background-image:url(/Public/Site/Icon/'+n+'.gif);" icon="/Public/Site/Icon/'+n+'.gif"></a>';
            }).join('');
            $('#default-icon-selete').html(str);
            $('#default-icon-selete a').click(function(e){
                var icon=$(this).attr('icon');
                Lat.SiteFormData.icon=icon;
                $('.icon-content',demo).css('background-image','url('+icon+')');
                return false;
            });
        }
        if($('#color-picker').html()==''){
            $('#color-picker').html(colorPicker());
            $('#color-seleter').click(function(e){
                $('#color-picker').toggle();
                return false;
            });
            $(document).click(function(){
                if($('#color-picker').css('display')!='none')$('#color-picker').hide();
            });
            $('#color-picker td').click(function(e){
                var color=$(this).attr('bgcolor');
                Lat.SiteFormData.titleColor=color;
                $('#color-picker').hide();
                $('.icon-content',demo).css({ 'color':color});
                return false;
            });
        }
        $("#icon-type-default").click();
    },
    iconUpload:function(result){
        var errMark='err:';
        if(result.indexOf(errMark)==0){
        return this.showMessage('上传失败：'+result.replace(errMark,''));
        }
        this.SiteFormData.icon=result;
        $('#site-icon-demo .icon-content').css('background-image','url('+result+')');
        },
        initSetDeskBg:function(){
        $('#setDeskBgOk').click(function(){
        $('#setDeskBgForm').attr('action','/?action=deskBgUpload&deskId='+Lat.DefaultDesk+'&bgType='+($('#bgType').attr('checked')?1:0)).submit();
        $('#setDeskBgPress').html('上传中，请稍候...');
        return false;
        });
        },
        deskBgUpload:function(result){
        $('#setDeskBgPress').html('整图上传成功，现在转入桌面...');
        setTimeout(function(){
        location.href='?'+Lat.DefaultDesk;
        },500);
    },
    
    
    exchange:function(sourceId,targetId){
        Lat.DragElement=Lat.TargetElement;
        var sourceElement=$('#'+sourceId);
        var targetElement=$('#'+targetId);
        targetElement.removeClass('dragOver');
        var _html=targetElement.html();
        targetElement.html(sourceElement.html());
        sourceElement.html(_html);
        var _data=Lat.Data[sourceId];
        Lat.Data[sourceId]=Lat.Data[targetId];
        Lat.Data[targetId]=_data;
        if(this.State!=2)return;
        var data=$R(0,51).map(function(id){
        return Lat.Data[id]?Lat.Data[id][0]:0;
        }).join(',');
        jQuery.post('?action=editDesk','id='+this.DefaultDesk+'&data='+data);
        },
        updateSite:function(id,data){
        data.id=data.id||0;
        this.updateSiteData(id,data);
        Lat.initBox(id);
        var queryStr='deskId='+this.DefaultDesk+'&index='+id+'&data='+this.Data[id].join(',');
        jQuery.post('?action=updateDeskSite',queryStr,function(result){
        if(result){
        data.id=parseInt(result);
        if(!data.id)return false;
        Lat.updateSiteData(id,data);
        }
        });
    },
    
    
    updateSiteData:function(id,data){
        if(data)data=[data.id,data.title,data.url,data.bgColor,data.icon,data.titleColor];
        this.Data[id]=data;
        this._Data[this.DefaultDesk].data[id]=data;
        },
        addSite:function(id){
        if(this.State==0)return $('#loginDialog').click();
        Lat.initAddSiteData();
        $('#addIconDialog').click();
    },
    editSite:function(id){
        this.UpdateSiteId=id;
        this.initAddSiteData(this.Data[id]);
        $('#addIconDialog').click();
        },
        delSite:function(id){
        this.updateSiteData(id,null);
        Lat.initBox(id);
        jQuery.post('?action=delDeskSite','deskId='+this.DefaultDesk+'&index='+id);
    },
    copySite:function(id){
        $("#copySiteIndex").val(id);
        $("#copySiteId").val(this.Data[id][0]);
        var html='';
        if(this.State==2){
        this._Data.each(function(desk){
        var data=desk.value;
        if(data.id!=Lat.DefaultDesk){
        html+='<option value="'+data.id+'">'+data.title+'</option>';
        }
        });
        }else if(this.State==1){
        this.MyDesks.each(function(data){
        html+='<option value="'+data.id+'">'+data.title+'</option>';
        });
        }
        $('#copySiteForm select').html(html);
        $('#copySiteDialog').click();
    },
    _dragAction:function(action){
        if(action==this.ActionName)return;
        $('#'+this.TempElement).removeClass('dragOver');
        this.TempElement=null;
        this.ActionName=action;
        $('#'+action).addClass('hover');
        },
        cmd:function(action){
        var id=this.DragElement;
        if(this.State==0){
        $('#loginDialog').click();
        }else{
        this[action.split('-')[1]+'Site'](id);
        }
        this.ShowAction=false;
        this.ActionName=null;
        setTimeout(function(){
        $('#'+action).removeClass('hover');
        $("#dropBox").hide();
        $('#'+(Lat.State==2?'opt-mine':'opt-common')).hide();
        Lat.Draging=false;
        },action=='mine-del'?0:500);
    },
    _dragShowAction:function(){
        this.ShowAction=this.Draging;
        $('#search-box').hide();
        if(this.Draging){
        if(this.State==2){
        $('#opt-mine').show();
        }else{
        $('#opt-common').show();
        }
        }else{
        if(this.State==2){
        $('#opt-mine').hide();
        }else{
        $('#opt-common').hide();
        }
        }
    },
    _getTarget:function(e){
        var pos=$.getMousePosition(e);
        var x=pos.x-this.ContainerPos.left;
        var y=pos.y-this.ContainerPos.top;
        var id=this._getTargetId(x,y);
        if(id==null)return;
        this.DragState=1;
        if(typeof id=='string'){
        if(id!=this.ActionName)$('#'+this.ActionName).removeClass('hover');
        this._dragAction(id);
        return false;
        }
        if(this.ActionName){
        $('#'+this.ActionName).removeClass('hover');
        this.ActionName=null;
        }
        id=id-1;
        Lat.TargetElement=id;
        if(Lat.TargetElement==this.TempElement)return;
        this.dragOverBox(Lat.TargetElement);
        this.TempElement=Lat.TargetElement;
    },
    _getTargetId:function(x,y){
        var _x=x%90;
        var _y=y%90;
        var xn=Math.ceil(x/90);
        var yn=Math.ceil(y/90);
        if(yn>=3&&yn<=4&&xn>=4&&xn<=7){
        if(y<90*2+10||x>90*7)return null;
        if(this.State==2){
        if(x<=90*3+116)return'mine-edit';
        if(x<=90*3+116+118)return'mine-del';
        return'mine-copy';
        }else{
        return'common-copy';
        }
        }
        if(_x<10||_y>80)return null;
        if(yn<=2)return 10*(yn-1)+xn;
        if(yn>=5)return 32+10*(yn-5)+xn;
        if(xn<=3)return 20+3*(yn-3)+xn;
        if(xn>=8)return 26+3*(yn-3)+(xn-7);
        return null;
    },
    _drag:function(e){
    var id=Lat.TargetElement;
    if(id<0||id>51){
    id=Lat.TargetElement=Lat.DragElement;
    }
    $('#dropBox').animate({
    left:Lat.PosData[id][0],
    top:Lat.PosData[id][1]
    },200,function(){
    Lat.Draging=false;
    if(Lat.TargetElement!=Lat.DragElement){
    Lat.exchange(Lat.DragElement,Lat.TargetElement);
    }else{
    $('#'+id).removeClass('dragOver');
    }
    Lat._dragShowAction();
    });
    },
    mouseOverBox:function(e){
        if(this.Draging)return;
        if(!this.MouseOut)this.mouseOutBox();
        this.MouseOut=false;
        var id=e.id;
        if(!this.Data[id]){
        this.UpdateSiteId=id;
        $("#addIcon").css({left:this.PosData[id][0],top:this.PosData[id][1]}).show();
        }else{
        $("#addIcon").css({left:-5000});
        this.DragElement=this.TempElement=this.TargetElement=id;
        var dragHTML=$(e).html().replace(/id=[^> ]*/img,'');
        $('.icon-inner',e).addClass('on');
        $("#dropBox").html(dragHTML).css({left:this.PosData[id][0],top:this.PosData[id][1]}).show();
        }
    },
    mouseOutBox:function(e){
        if(this.Draging)return;
        $("#dropBox").hide();
        if($.browser.msie)window.status='';
        $('#'+this.DragElement+' .icon-inner').removeClass('on');
        this.MouseOut=true;
    },
    clickBox:function(id){
        if(this.Draging)return;
        var url=$('#'+id+' .icon-content').attr('rel');
        window.open(url,'');
    },
    dragOverBox:function(id){
        $('#'+this.TempElement).removeClass('dragOver');
        $('#'+id).addClass('dragOver');
    }
};


$(document).ready(function(){
    setTimeout(function(){
        if(location.href.include('?')){
            var deskId=location.href.split('?')[1];
            if(deskId&&　Lat._Data[deskId]) Lat.DefaultDesk=deskId;
        }
        Lat.init();
    },1000);
});

function initForm(data,form){
    form=$E(form);
    for(var key in data){
    if(!form[key])continue;
    var value=data[key];
    if(value===null)continue;
    if(typeof(value)!='array')value=[$C(value)];
    $(form[key]).val(value);
    }
}
function colorPicker(){
    var arr_color1=['00','33','66'];
    var arr_color2=['00','33','66','99','cc','ff'];
    var arr_color3=['000000','333333','666666','999999','cccccc','ffffff','ff0000','00ff00','0000ff','ffff00','ff00ff','00ffff'];
    var html='<table cellpadding="0" cellspacing="1" border="0" bgcolor="#000000">';
    var idx=0;
    for(var k=0;k<arr_color2.length;k++){
    html+='<tr>';
    html+='<td bgcolor="#'+arr_color3[idx]+'"></td>';
    idx++;
    for(i=0;i<arr_color1.length;i++){
    for(j=0;j<arr_color2.length;j++){
    html+='<td bgcolor="#'+arr_color1[i]+arr_color2[j]+arr_color2[k]+'"></td>';
    }
    }
    html+='</tr>';
    }
    var arr_color1=['99','cc','ff'];
    for(k=0;k<arr_color2.length;k++){
    html+='<tr>';
    html+='<td bgcolor="#'+arr_color3[idx]+'"></td>';
    idx++;
    for(i=0;i<arr_color1.length;i++){
    for(j=0;j<arr_color2.length;j++){
    html+='<td bgcolor="#'+arr_color1[i]+arr_color2[j]+arr_color2[k]+'"></td>';
    }
    }
    html+='</tr>';
    }
    html+='</table>';
    return html;
}